package com.ibeetl.starter;

import java.util.Properties;

import javax.sql.DataSource;

import org.beetl.core.om.ObjectUtil;
import org.beetl.sql.core.ClasspathLoader;
import org.beetl.sql.core.Interceptor;
import org.beetl.sql.core.NameConversion;
import org.beetl.sql.core.db.DBStyle;
import org.beetl.sql.ext.DebugInterceptor;
import org.beetl.sql.ext.spring4.BeetlSqlDataSource;
import org.beetl.sql.ext.spring4.BeetlSqlScannerConfigurer;
import org.beetl.sql.ext.spring4.SqlManagerFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

@Configuration
@ConditionalOnBean(DataSource.class)
public class BeetlSqlConfig {
	
	
	@Bean(name = "beetlSqlScannerConfigurer")
	@ConditionalOnMissingBean(BeetlSqlScannerConfigurer.class)
	public BeetlSqlScannerConfigurer getBeetlSqlScannerConfigurer(Environment env) {
		BeetlSqlProperties beetlSqlProperties = new BeetlSqlProperties(env);
		BeetlSqlScannerConfigurer conf = new BeetlSqlScannerConfigurer();
		conf.setBasePackage(beetlSqlProperties.getBasePackage());
		conf.setDaoSuffix(beetlSqlProperties.getDaoSuffix());
		conf.setSqlManagerFactoryBeanName("sqlManagerFactoryBean");
		return conf;
	}

	@Bean(name = "sqlManagerFactoryBean")
	@ConditionalOnMissingBean(SqlManagerFactoryBean.class)
	public SqlManagerFactoryBean getSqlManagerFactoryBean(BeetlSqlDataSource source,Environment env) {
		
		BeetlSqlProperties beetlSqlProperties = new BeetlSqlProperties(env);
		SqlManagerFactoryBean factory = new SqlManagerFactoryBean();
		
		factory.setCs(source);
		factory.setDbStyle((DBStyle)ObjectUtil.tryInstance(beetlSqlProperties.getDbStyle()));
		factory.setInterceptors(beetlSqlProperties.dev ? new Interceptor[] { new DebugInterceptor() } : new Interceptor[0]);
		factory.setNc((NameConversion)ObjectUtil.tryInstance(beetlSqlProperties.getNameConversion()));
		ClasspathLoader loader = new ClasspathLoader(beetlSqlProperties.getSqlPath());
		//不能直接设置通过loader的autocheck
		Properties ps = new Properties();
		ps.put("PRODUCT_MODE", beetlSqlProperties.dev?"false":"true");
		factory.setExtProperties(ps);
		factory.setSqlLoader(loader);
		return factory;
	}
	
	@Bean
	@ConditionalOnMissingBean(BeetlSqlDataSource.class)
	public BeetlSqlDataSource beetlSqlDataSource(@Qualifier("dataSource")  DataSource dataSource){
		BeetlSqlDataSource source = new BeetlSqlDataSource();
		source.setMasterSource(dataSource);
		return source;
	}
	
	

}
